package com.blog.cloud.sms.controller;

import com.blog.cloud.core.utils.R;
import com.blog.cloud.sms.constants.SmsConstrant;
import com.blog.cloud.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping(value = "/sms")
public class SmsController {

    @Autowired
    private SmsService tencentSmsService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/tencent/send")
    public R<String> sendSmsByTencent(@RequestBody String mobile) {
        // 接口防刷，防止同一手机号在60秒内多次重复发送
        Long expireTime = stringRedisTemplate.opsForValue().getOperations().getExpire(SmsConstrant.SMS_CODE_CACHE_PREFIX + mobile, TimeUnit.MINUTES);
        if (Objects.nonNull(expireTime) && expireTime >= 1) {
            return R.failed("验证码发送过于频繁,请稍后再发");
        }
        return tencentSmsService.sendSms(mobile);
    }
}
